#include "watcherfile.h"
#include <QDebug>
#include <QDir>
#include <QDateTime>

WatcherFile::WatcherFile(QObject *parent) : QObject(parent)
{
    watch =new QFileSystemWatcher;
    connect(watch, SIGNAL(directoryChanged(QString)), this, SLOT(directoryUpdated(QString)));
    connect(watch, SIGNAL(fileChanged(QString)), this, SLOT(fileUpdated(QString)));
}

///
/// \brief WatcherFile::initWathcfile
/// \param path
///初始目录进行监控 最后10个文件
/// 如果文件超过3天 移到备份目录
void WatcherFile::initWathcfile(const QString& path){

    QDir *dir;
    dir=new QDir(path);
    QStringList filter;
    filter<<"*.txt";
    dir->setNameFilters(filter);
    //按时间倒序排序
    QList<QFileInfo> fileInfo = QList<QFileInfo>(dir->entryInfoList(filter,QDir::AllEntries,QDir::Time));


    if(fileInfo.size() == 0)
        return;

    //三天前的时间
    QDateTime currtime =QDateTime::currentDateTime();
    currtime=currtime.addDays(-3);

    for(int i = 0; i < fileInfo.size(); i++) {
        qDebug()<<  fileInfo.at(i).absoluteFilePath();
        qDebug()<<  fileInfo.at(i).lastModified().toLocalTime().toString("yyyy-MM-dd hh:mm:ss");

        //监控
        if(i<10){
            addWatchFile(fileInfo.at(i).absoluteFilePath());
        }

        //移走三天前的文件
        if(fileInfo.at(i).lastModified().toTime_t()<currtime.toTime_t()){

        }
    }


}

void  WatcherFile::addWatchDir(const QString &dir){
    watchpath=dir;
    watch->addPath(dir);
    const QDir dirw(dir);
    m_watchDirMap[dir] = dirw.entryList(QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files, QDir::DirsFirst);

    initWathcfile(dir);
}

void  WatcherFile::addWatchFile(const QString &file){
    watch->addPath(file);
    wathchfiles.append(file);

    if(wathchfiles.length()<10)
        return;
    //超过10个移除
    watch->removePath(wathchfiles[0]);
    wathchfiles.removeFirst();
}

///
/// \brief WatcherFile::directoryUpdated
/// \param path
///目录发生变化时，通知，
/// 新加文件时，加入到文件监控
void WatcherFile::directoryUpdated(const QString &path){
    qDebug()<<"directoryUpdated:"<< path;

    // 比较最新的内容和保存的内容找出区别(变化)
    QStringList currEntryList = m_watchDirMap[path];
    const QDir dir(path);

    QStringList newEntryList = dir.entryList(QDir::NoDotAndDotDot  | QDir::AllDirs | QDir::Files, QDir::DirsFirst);

    QSet<QString> newDirSet = QSet<QString>::fromList(newEntryList);
    QSet<QString> currentDirSet = QSet<QString>::fromList(currEntryList);

    // 添加了文件
    QSet<QString> nFiles = newDirSet - currentDirSet;
    QStringList newFiles = nFiles.toList();

    // 更新当前设置
    m_watchDirMap[path] = newEntryList;

    if(newFiles.isEmpty())
        return;

    //有新加的文件
    foreach(QString item,newFiles){
           qDebug()<<"new:"<<item;
        QString f=watchpath+"/"+item;
        this->addWatchFile(f);
        this->fileUpdated(f);
    }
}

void WatcherFile::fileUpdated(const QString &path){
    qDebug()<<"fileUpdated:"<< path;
    emit fileChange(path);
}
